/**
 * Created by xuan on 8/19/15.
 */
/**
 * 案场日报
 */
define(function (require) {
    'use strict';
    var $ = require('jquery');
    var angular = require('angular');
    var util = require('util');
    require('angular-ui');
    var _ = require('underscore');
    require('angular-interceptor');
    require('/ydxs_static/public/js/plugins/filterCombobox');
    require('/ydxs_static/public/js/service/init_settings/equationService');
    require('./team_service');
    require('/static_public/js/angular_directive/projectTreeSelector');
    var moment = require('/static_public/node_modules/moment/moment.cmd');
    angular.module('dailyReportApp',['ngInterceptor','equationServiceApp','teamServiceApp','filterCombobox','ngUI','projectTreeSelector'])

        .factory('dailyReportService',['$http',function($http){
            function httpGet(url,data){
                url = '/api/index.php?r=' + url ;
                return $http.get(url,{params:data});
            }
            return {
                getQueryParams : function(scope){
                    return {
                        proj_id: scope.curProjectId,
                        start_time: scope.queryUnReset.startTime,
                        end_time: scope.queryUnReset.endTime,
                        index : scope.query.pageIndex-1,
                        page_size : scope.queryUnReset.pageSize,
                        team_id: scope.query.teamId,
                        group_id: scope.query.groupId,
                        user_id: scope.query.salerId,
                        cst_info : scope.query.cstInfo,
                        date_mode: scope.queryUnReset.dateMode
                    };
                },
                getList : function(scope){
                    var url = scope.queryUnReset.url;
                    var data = this.getQueryParams(scope);
                    if(scope.countType === 'rengou'){
                        data.type = 'rg';
                    }else if(scope.countType === 'qianyue'){
                        data.type = 'qy';
                    }
                    return httpGet(url,data)
                        .then(function(res){
                            scope.dailyReportList = res.data.data.info || [];
                            scope.query.total = res.data.data.sum;

                        }).finally(function(){
                            scope.loading = false ;
                        });
                },
                getProjectList :function(scope){
                    var url = 'ydxs/project/list/';
                    var data = {flag:0, jointparent:1};
                    httpGet(url,data).then(function(res){
                        var data = res.data.data;
                        //var projectList = [];
                        //if (!data.citys) {
                            //return;
                        //}
                        //for (var i = 0; i < data.citys.length; i++) {
                            //projectList = projectList.concat(data.citys[i].list);
                        //}
                        //scope.projectList = projectList;
                        //if (res.data.length) {
                            //scope.curProjectId = res.data[0].p_projectId;
                        //}
                        scope.projectList = data;
                    });
                },
                getAmountData : function(scope){
                    var url = 'ydxs/sale-report/total';
                    var data = {
                        proj_id: scope.curProjectId,
                        start_time: scope.queryUnReset.startTime,
                        end_time: scope.queryUnReset.endTime,
                        date_mode: scope.queryUnReset.dateMode
                    };
                    return httpGet(url,data).then(function(res){
                        scope.amountData = res.data.data;
                    });
                }
            };
        }])
        .controller('dailyReportCtrl',['$scope','$q','dailyReportService','teamService','equationService',function($scope,$q,dailyReportService,teamService,equationService){
            /* 局部变量 start */
            var fmt = 'YYYY-MM-DD';

            var initQuery = {
                pageIndex : 1,
                teamId : '',
                groupId : '',
                groupDisabled : true,
                salerId : '',
                salerDisabled : true,
                cstInfo : ''
            };
            function refreshPageData(){
                $scope.resetQuery();
                $scope.getConfig();
                $scope.dailyLoading = true;
                $q.all([dailyReportService.getAmountData($scope),dailyReportService.getList($scope)])
                    .then(function(){
                        $scope.dailyLoading = false;
                    });
            }
            function refreshDictData(){
                teamService.getTeamList($scope);
            }
            /* 局部变量 end */

            /* $scope变量 start */
            $scope.curProjectId = '';

            $scope.dailyType = 'day';

            $scope.countType = 'laidian';

            $scope.dailyLoading = true;

            $scope.query = angular.copy(initQuery);

            $scope.queryUnReset = {
                pageSize : 10,
                url : 'ydxs/sale-report/call-list',
                dateMode: 1,//搜索日期格式，1本日，2本周，3本月，4本年，9时间段
                startTime : moment().subtract(1, 'month').format(fmt),
                endTime : moment().format(fmt)
            };

            $scope.dayDate = moment().format(fmt);
            $scope.weekFirst = moment().startOf('isoWeek').format(fmt);
            $scope.weekEnd = moment().endOf('isoWeek').format(fmt);
            $scope.monthFirst = moment().startOf('month').format(fmt);
            $scope.monthEnd = moment().endOf('month').format(fmt);

            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$watch('curProjectId', function () {
                if($scope.curProjectId){
                    refreshPageData();
                    refreshDictData();
                }
            });
            $scope.$watch('query.teamId', function (newValue, oldValue) {
                if(newValue && newValue !== oldValue){
                    var groups = _.find($scope.teamDatas,function(item){ return item.team_id === newValue; }).groups;
                    $scope.groupList = _.map(groups, function (item) {
                        item.text = item.group_name;
                        return item;
                    });
                    $scope.query.groupDisabled = false;
                }
            });
            $scope.$watch('query.groupId', function (newValue, oldValue) {
                if(newValue && newValue !== oldValue){
                    var groups = _.find($scope.teamDatas,function(item){ return item.team_id === $scope.query.teamId; }).groups;
                    var salers = _.find(groups,function(item){ return item.group_id === newValue; }).salers;
                    $scope.salerList = _.map(salers, function (item) {
                        item.text = item.user_name;
                        return item;
                    });
                    $scope.query.salerDisabled = false;
                }
            });
            /* $scope变量 watch end */

            /* $scope方法 start */
            $scope.getList = function(pageIndex){
                pageIndex || (pageIndex = 1);
                $scope.query.pageIndex = pageIndex;
                dailyReportService.getList($scope);
            };

            $scope.getCountList = function(){
                dailyReportService.getAmountData($scope);
                $scope.getConfig();
                $scope.getList();
            };

            $scope.resetQuery = function () {
                $scope.query = angular.copy(initQuery);
            };
            $scope.changeDailyType = function (dailyType) {
                $scope.dailyType = dailyType;
                if(dailyType === 'day'){
                    $scope.queryUnReset.dateMode = 1;
                }else if(dailyType === 'week'){
                    $scope.queryUnReset.dateMode = 2;
                }else if(dailyType === 'month'){
                    $scope.queryUnReset.dateMode = 3;
                }else if(dailyType === 'during'){
                    $scope.queryUnReset.dateMode = 9;
                }
                refreshPageData();
            };
            $scope.changeCountType = function (countType) {
                // $scope.isShowDetail == 0 and （认购或签约时），不显示明细
                if(!$scope.amountData.isShowDetail && (countType === 'rengou' || countType === 'qianyue')){
                    return ;
                }
                $scope.countType = countType;
                if(countType === 'laidian'){
                    $scope.queryUnReset.url = 'ydxs/sale-report/call-list';
                }else if(countType === 'laifan'){
                    $scope.queryUnReset.url = 'ydxs/sale-report/visit-list';
                }else if(countType === 'renchou'){
                    $scope.queryUnReset.url = 'ydxs/sale-report/get-confess-list';
                }else if(countType === 'rengou' || countType === 'qianyue'){
                    $scope.queryUnReset.url = 'ydxs/sale-report/list';
                }
                $scope.resetQuery();
                $scope.countLoading = true;
                $q.all(dailyReportService.getList($scope))
                    .then(function(){
                    $scope.countLoading = false;
                });
            };
            $scope.exportData = function () {
                var data = dailyReportService.getQueryParams($scope);
                data.token = util.getToken();
                if($scope.countType === 'laidian'){
                    data.type = 1;
                    location.href = '/api/index.php?r=ydxs/sale-report/export-call-and-list&'+$.param(data);
                }else if($scope.countType === 'laifan'){
                    data.type = 2;
                    location.href = '/api/index.php?r=ydxs/sale-report/export-call-and-list&'+$.param(data);
                }else if($scope.countType === 'renchou'){
                    location.href = '/api/index.php?r=ydxs/sale-report/export-confess-list&'+$.param(data);
                }else if($scope.countType === 'rengou'){
                    data.type = 'rg';
                    data.is_export = '1';
                    location.href = '/api/index.php?r=ydxs/sale-report/list&'+$.param(data);
                }else if($scope.countType === 'qianyue'){
                    data.type = 'qy';
                    data.is_export = '1';
                    location.href = '/api/index.php?r=ydxs/sale-report/list&'+$.param(data);
                }

            };
            $scope.filterDate = function (str) {
                return str?str.substr(0,10):'';
            };

            $scope.getConfig = function () {
                equationService.getEquation('all').then(function(data){
                    $scope.rgkjEquation = data.rgkjEquation;
                    $scope.qykjEquation = data.qykjEquation;
                });
            };
            /* $scope方法 end */

            // init
            dailyReportService.getProjectList($scope);

        }]);
    angular.element(document).ready(function () {
        angular.bootstrap(document, ['dailyReportApp']);
    });
});
